import { Scene } from "../../../../../Core/Module/Entity/Scene";
import { Log } from "../../../../../Core/Module/Log/Log";
import { PingComponent } from "../../../../Model/Client/Demo/Ping/PingComponent";
import { SessionComponent } from "../../../../Model/Client/Demo/Session/SessionComponent";
import { NetClientComponent } from "../../../../Model/Client/Module/Message/NetClientComponent";
import { C2G_LoginGate, C2R_Login, G2C_LoginGate, R2C_Login } from "../../../../Model/Generate/Share/Message/OuterMessage_C_10001";
import { ErrorCode } from "../../../../Model/Share/Module/Message/ErrorCode";
import { Session } from "../../../../Model/Share/Module/Message/Session";
import { ConstValue } from "../../../Share/ConstValue";

export class LoginHelper {

    public static async Login(clientScene: Scene, account: string, password: string) {
        let r2CLogin: R2C_Login = null;
        let accountSession: Session = null;
        let address: string = `ws://${ConstValue.RouterHttpHost}:${ConstValue.RealmPort}`;
        clientScene.AddComponent<NetClientComponent, string>(NetClientComponent, address);
        try {
            accountSession = await clientScene.GetComponent<NetClientComponent>(NetClientComponent).Create(address);
            const c2RLogin = new C2R_Login();
            c2RLogin.Account = account;
            c2RLogin.Password = password;
            r2CLogin = await accountSession.Call(c2RLogin) as R2C_Login;
        } catch (e) {
            accountSession?.Dispose();
            Log.Error(e);
            return ErrorCode.ERR_NetWorkError;
        }
        if (r2CLogin.Error != ErrorCode.ERR_Success) {
            accountSession?.Dispose();
            return r2CLogin.Error;
        }
        // 创建一个gate Session,并且保存到SessionComponent中
        let gateSession = await clientScene.GetComponent<NetClientComponent>(NetClientComponent).Create(`ws://${r2CLogin.IP}:${r2CLogin.Port}`);

        clientScene.AddComponent<SessionComponent>(SessionComponent).Session = gateSession;
        clientScene.GetComponent<SessionComponent>(SessionComponent).Session.AddComponent<PingComponent>(PingComponent);

        const c2GLoginGate = new C2G_LoginGate();
        c2GLoginGate.Key = r2CLogin.Key;
        c2GLoginGate.GateId = r2CLogin.GateId
        const g2CLoginGate = await gateSession.Call(c2GLoginGate) as G2C_LoginGate;

        console.log(`登录成功`);
        console.log(r2CLogin.GateId);
        console.log(g2CLoginGate.PlayerId);

        return ErrorCode.ERR_Success;
    }

}